import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { RiskControlScheme, IRiskControlQueryParams } from '@shared/interfaces/risk-control'
import { NzMessageService } from 'ng-zorro-antd'
import { I18NService } from '@core'
import { Router, ActivatedRoute } from '@angular/router'
import { ISearchSchema, ISearchOption } from '@shared/interfaces/search'
import { STColumn } from '@delon/abc'
import { ESearchType, EStatus } from '@shared/enums'
import { IAamsItem } from '@shared/components/aams-select/aams-select.interface'
import { RiskService } from '../risk.service'
import { RiskStoreService } from '../new/risk-store.service'
import { StatusTextMap, RiskTypeMap } from '@shared/interfaces/common'
import { ModalService } from '@shared/services/modal.service'
import { SettingsService } from '@delon/theme'
import { AcquirerService } from '../../acquirer/acquirer.service'

@Component({
  selector: 'app-risk-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../../shared/styles/table.less'],
})
export class RiskListComponent extends ListBaseClass<RiskControlScheme, IRiskControlQueryParams>
implements OnInit {
  @ViewChild('tplAcquirer') tplAcquirer: TemplateRef<void>

  selectedAcquirer: IAamsItem

  StatusTextMap = StatusTextMap

  RiskTypeMap = RiskTypeMap

  riskCategoryOptions: ISearchOption[] = [
    { label: this.trans('RISK_CTRL_CATEGORY.NORMAL'), value: 'normal' },
    { label: this.trans('RISK_CTRL_CATEGORY.SPECIAL'), value: 'special' },
  ]
  statusOptions = [
    { label: this.trans('GENERAL.STATUS.NORMAL'), value: 'normal' },
    { label: this.trans('GENERAL.STATUS.FREEZE'), value: 'freeze' },
  ]

  searchSchema: ISearchSchema[] = []

  customSchema: ISearchSchema[] = []

  data: RiskControlScheme[] = []
  columns: STColumn[] = [
    {
      type: 'link',
      title: '风控方案代码',
      i18n: 'RISK_CTRL.SCHEME_CODE',
      index: 'schemeCode',
      width: '150px',
      className: 'text-center',
      fixed: 'left',
      click: this.goDetail.bind(this),
    },
    {
      title: '风控方案名称',
      i18n: 'RISK_CTRL.SCHEME_NAME',
      index: 'schemeName',
      width: '150px',
      className: 'text-left',
    },
    {
      title: '方案描述',
      i18n: 'RISK_CTRL.SCHEME_DESC',
      index: 'remark',
      className: 'text-center',
      width: '150px',
    },
    {
      title: '风控方案类型',
      i18n: 'RISK_CTRL.CATEGORY',
      index: 'category',
      className: 'text-center',
      width: '150px',
      render: 'type',
    },
    {
      title: '归属机构',
      i18n: 'ROLE.OWNER_INSTITUTION',
      index: 'insCode',
      className: 'text-center',
      width: '100px',
    },
    {
      title: '更新时间',
      i18n: 'GENERAL.INFO.UPDATED_AT',
      index: 'updatedAt',
      className: 'text-center',
      width: '200px',
      type: 'date',
      dateFormat: 'YYYY-MM-DD HH:mm',
    },
    {
      title: '状态',
      i18n: 'GENERAL.INFO.STATUS',
      index: 'status',
      className: 'text-center',
      width: '100px',
      render: 'status'
    },
    // 操作按钮
    {
      title: '操作',
      width: '150px',
      className: 'text-center p-xs',
      fixed: 'right',
      buttons: [
        {
          text: '',
          click: this.freezeDialog.bind(this),
          icon: {
            iconfont: 'icon-lock-twotone',
            type: 'iconfont',
          },
          iif: record => record.status === EStatus.Normal,
        },
        {
          text: '',
          click: this.unfreezeDialog.bind(this),
          icon: {
            iconfont: 'icon-lock-twotone',
            type: 'iconfont',
          },
          iif: record => record.status === EStatus.Freeze,
        },
        {
          text: '',
          click: this.copyDialog.bind(this),
          icon: {
            iconfont: 'icon-copy-circle-twotone',
            type: 'iconfont',
          },
        },
      ]
    }
  ]

  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    private riskService: RiskService,
    public riskStore: RiskStoreService,
    private modalService: ModalService,
    public acquirerService: AcquirerService,
    public settings: SettingsService,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit() {
    this.initSearchParams()
    this.parseParams().subscribe(() => {
      this.queryTableDataWithParams()
    })
    this.initialAAMSFilter()
  }

  initialAAMSFilter() {
    this.initAcquirer()
  }

  initSearchParams(): void {
    this.searchSchema = [
      {
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        index: ['submittedAtFrom', 'submittedAtTo'],
        type: ESearchType.dateRange,
        value: [],
      },
      {
        label: 'GENERAL.INFO.UPDATED _AT',
        labelI18n: 'GENERAL.INFO.UPDATED_AT',
        index: ['updatedAtFrom', 'updatedAtTo'],
        type: ESearchType.dateRange,
        value: [],
      },
      {
        label: 'ROLE.OWNER_INS TITUTION',
        labelI18n: 'ROLE.OWNER_INSTITUTION',
        index: 'insCode',
        component: this.tplAcquirer,
        customFunc: () => this.selectedAcquirer && this.selectedAcquirer.code,
      },
      {
        label: 'RISK_CTR L.SCHEME_CODE',
        labelI18n: 'RISK_CTRL.SCHEME_CODE',
        index: 'schemeCode',
        type: ESearchType.input,
      },
      {
        label: 'RIS K_CTRL.SCHEME_NAME',
        labelI18n: 'RISK_CTRL.SCHEME_NAME',
        index: 'schemeName',
        type: ESearchType.input,
      },
      {
        label: 'RISK_CTRL.CATEGORY',
        labelI18n: 'RISK_CTRL.CATEGORY',
        index: 'category',
        type: ESearchType.selection,
        options: this.riskCategoryOptions
      },
      {
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        type: ESearchType.selection,
        options: this.statusOptions,
      }
    ]
  }

  goAdd(): void {
    this.router.navigate(['../new'], { relativeTo: this.route })
  }

  goDetail(scheme: RiskControlScheme): void {
    const { schemeCode } = scheme
    this.router.navigate([`../${schemeCode}`], { relativeTo: this.route })
  }

  freezeDialog(record: RiskControlScheme): void {
    const { schemeCode, schemeName } = record
    const msg = this.trans('GENERAL.NOTIFICATION.RC_SCHEME_FREEZE_CONFIRM', {schemeName})
    this.modalService.freezeAndUnFreeze(msg).subscribe(
      (isOk) => {
        if (!isOk) return
        this.freeze(schemeCode)
      }
    )
  }

  unfreezeDialog(record: RiskControlScheme): void {
    const { schemeCode, schemeName } = record
    const msg = this.trans('GENERAL.NOTIFICATION.RC_SCHEME_UNFREEZE_CONFIRM', {schemeName})
    this.modalService.freezeAndUnFreeze(msg).subscribe(
      (isOk) => {
        if (!isOk) return
        this.unfreeze(schemeCode)
      }
    )
  }

  freeze(schemeCode: string): void {
    this.riskService.freeze(schemeCode).subscribe(
      () => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.FREEZE_SUCCESS'))
        this.st.reload()
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.FREEZE_FAIL'))
      }
    )

  }

  unfreeze(schemeCode: string): void {
    this.riskService.unfreeze(schemeCode).subscribe(
      () => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_SUCCESS'))
        this.st.reload()
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.UNFREEZE_FAIL'))
      }
    )

  }
  // 点击复制跳转新建页面
  copyDialog(record: RiskControlScheme): void {
    console.log(record)
    this.acquirerService.getOne(record.insCode as string).subscribe(data => {
      record.insCode = {
        code: data.institution.common.insCode,
        num: data.institution.common.insCode,
        level: 'institution',
        nameEN: data.institution.common.insNameEN,
        name: data.institution.common.insName,
      }
      this.riskStore.setValue(record)
      this.router.navigateByUrl('/risk/new')
    })
  }
  renderList(res): void {
    const { data, total } = res
    this.data = data || []
    this.total = total
    this.loading = false
  }

  queryTableDataWithParams(): void {
    this.loading = true
    this.riskService
      .getList(this.params)
      .subscribe(
        this.renderList.bind(this),
        this.getListError.bind(this)
      )
  }
}
